<template>
	<el-dialog
		title="修改收发货地址信息"
		v-model="dialogVisible"
		:destroy-on-close="true"
		width="800px"
	>
		<div class="address-form">
			<!-- 订单号 -->
			<div class="form-item mb-4">
				<span class="label">订单编号：</span>
				<span>{{ formData.orderNo }}</span>
			</div>

			<div class="address-content">
				<!-- 发货信息 -->
				<div class="sender-info" :class="{ active: activeTab === 'sender' }">
					<div class="section-header" @click="activeTab = 'sender'">
						<span class="title">发</span>
					</div>
					<div class="section-content">
						<el-form
							ref="senderFormRef"
							:model="formData.sender"
							:rules="rules"
							label-width="100px"
						>
							<el-form-item label="联系人" prop="contact" required>
								<el-input v-model="formData.sender.contact">
									<template #append>
										<el-button @click="handleSelectAddress('sender')"
											>地址簿</el-button
										>
									</template>
								</el-input>
							</el-form-item>
							<el-form-item label="联系电话" prop="phone" required>
								<el-input v-model="formData.sender.phone" />
							</el-form-item>
							<el-form-item label="地址简称" prop="addressTitle" required>
								<el-input v-model="formData.sender.addressTitle" />
							</el-form-item>
							<el-form-item label="详细地址" prop="address" required>
								<el-input
									v-model="formData.sender.address"
									type="textarea"
									rows="2"
								/>
							</el-form-item>
							<el-form-item label="计划发货时间" prop="planTime" required>
								<el-date-picker
									v-model="formData.sender.planTime"
									type="datetime"
									placeholder="选择日期时间"
									class="!w-full"
								/>
							</el-form-item>
						</el-form>
					</div>
				</div>

				<!-- 收货信息 -->
				<div
					class="receiver-info"
					:class="{ active: activeTab === 'receiver' }"
				>
					<div class="section-header" @click="activeTab = 'receiver'">
						<span class="title">收</span>
					</div>
					<div class="section-content">
						<el-form
							ref="receiverFormRef"
							:model="formData.receiver"
							:rules="rules"
							label-width="100px"
						>
							<el-form-item label="联系人" prop="contact" required>
								<el-input v-model="formData.receiver.contact">
									<template #append>
										<el-button @click="handleSelectAddress('receiver')"
											>地址簿</el-button
										>
									</template>
								</el-input>
							</el-form-item>
							<el-form-item label="联系电话" prop="phone" required>
								<el-input v-model="formData.receiver.phone" />
							</el-form-item>
							<el-form-item label="地址简称" prop="addressTitle" required>
								<el-input v-model="formData.receiver.addressTitle" />
							</el-form-item>
							<el-form-item label="详细地址" prop="address" required>
								<el-input
									v-model="formData.receiver.address"
									type="textarea"
									rows="2"
								/>
							</el-form-item>
							<el-form-item label="计划收货时间" prop="planTime" required>
								<el-date-picker
									v-model="formData.receiver.planTime"
									type="datetime"
									placeholder="选择日期时间"
									class="!w-full"
								/>
							</el-form-item>
						</el-form>
					</div>
				</div>
			</div>

			<!-- 费用信息 -->
			<div class="cost-info mt-4">
				<div class="section-title mb-4">费用信息</div>
				<el-form :model="formData.cost" label-width="100px">
					<el-row :gutter="20">
						<el-col :span="8">
							<el-form-item label="费用合计" required>
								<el-input-number
									v-model="formData.cost.total"
									:min="0"
									:precision="2"
									class="!w-full"
								>
									<template #append>元</template>
								</el-input-number>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="基础费用" required>
								<el-input-number
									v-model="formData.cost.base"
									:min="0"
									:precision="2"
									class="!w-full"
								>
									<template #append>元</template>
								</el-input-number>
							</el-form-item>
						</el-col>
						<el-col :span="8">
							<el-form-item label="加急费用">
								<el-input-number
									v-model="formData.cost.urgent"
									:min="0"
									:precision="2"
									class="!w-full"
								>
									<template #append>元</template>
								</el-input-number>
							</el-form-item>
						</el-col>
					</el-row>
				</el-form>
			</div>
		</div>

		<template #footer>
			<el-button @click="handleCancel">取消</el-button>
			<el-button type="primary" @click="handleSubmit" :loading="submitting"
				>保存</el-button
			>
		</template>
	</el-dialog>

	<!-- 地址簿选择弹窗 -->
	<AddressSelect ref="addressSelectRef" @select="handleAddressSelect" />
</template>

<script setup lang="ts">
import { ref, reactive, watch } from 'vue';
import { ElMessage } from 'element-plus';
import AddressSelect from '/@/views/tscompany/CustomerMgmt/components/AddressSelect.vue';
const addressSelectRef = ref(null);

const props = defineProps({
	modelValue: {
		type: Boolean,
		default: false,
	},
	orderData: {
		type: Object,
		default: () => ({}),
	},
});

const emit = defineEmits(['update:modelValue', 'success']);

const dialogVisible = ref(false);
const activeTab = ref('sender');
const submitting = ref(false);
const senderFormRef = ref(null);
const receiverFormRef = ref(null);
const currentAddressType = ref('');

// 表单数据
const formData = reactive({
	orderNo: '',
	sender: {
		contact: '',
		phone: '',
		addressTitle: '',
		address: '',
		planTime: '',
	},
	receiver: {
		contact: '',
		phone: '',
		addressTitle: '',
		address: '',
		planTime: '',
	},
	cost: {
		total: 0,
		base: 0,
		urgent: 0,
	},
});

// 表单校验规则
const rules = {
	contact: [
		{ required: true, message: '请输入联系人', trigger: 'blur' },
		{ min: 2, max: 20, message: '联系人长度为2-20个字符', trigger: 'blur' },
	],
	phone: [
		{ required: true, message: '请输入联系电话', trigger: 'blur' },
		{
			pattern: /^1[3-9]\d{9}$/,
			message: '请输入正确的手机号',
			trigger: 'blur',
		},
	],
	addressTitle: [
		{ required: true, message: '请输入地址简称', trigger: 'blur' },
		{ min: 2, max: 20, message: '地址简称长度为2-20个字符', trigger: 'blur' },
	],
	address: [
		{ required: true, message: '请输入详细地址', trigger: 'blur' },
		{ min: 5, max: 100, message: '详细地址长度为5-100个字符', trigger: 'blur' },
	],
	planTime: [{ required: true, message: '请选择计划时间', trigger: 'change' }],
};

// 监听弹窗显示状态
watch(
	() => props.modelValue,
	(val) => {
		dialogVisible.value = val;
		if (val && props.orderData) {
			// 初始化表单数据
			formData.orderNo = props.orderData.orderNo;
			formData.sender = {
				contact: props.orderData.senderName,
				phone: props.orderData.senderPhone,
				addressTitle: props.orderData.senderAddressTitle || '',
				address: props.orderData.senderAddress,
				planTime: props.orderData.planSendTime,
			};
			formData.receiver = {
				contact: props.orderData.receiverName,
				phone: props.orderData.receiverPhone,
				addressTitle: props.orderData.receiverAddressTitle || '',
				address: props.orderData.receiverAddress,
				planTime: props.orderData.planReceiveTime,
			};
			formData.cost = {
				total: props.orderData.totalAmount || 0,
				base: props.orderData.baseAmount || 0,
				urgent: props.orderData.urgentAmount || 0,
			};
		}
	},
);

// 监听弹窗关闭
watch(dialogVisible, (val) => {
	emit('update:modelValue', val);
});

// 打开地址簿
const handleSelectAddress = (type) => {
	currentAddressType.value = type;
	addressSelectRef.value?.open();
};

// 选择地址回调
const handleAddressSelect = (address) => {
	const target =
		currentAddressType.value === 'sender' ? formData.sender : formData.receiver;
	target.contact = address.contact;
	target.phone = address.phone;
	target.addressTitle = address.title;
	target.address = address.detail;
};

// 取消
const handleCancel = () => {
	dialogVisible.value = false;
};

// 提交
const handleSubmit = async () => {
	// 验证发货和收货表单
	const [senderValid, receiverValid] = await Promise.all([
		senderFormRef.value?.validate().catch(() => false),
		receiverFormRef.value?.validate().catch(() => false),
	]);

	if (!senderValid || !receiverValid) {
		return;
	}

	submitting.value = true;
	try {
		// TODO: 调用保存接口
		console.log('提交的数据：', formData);
		ElMessage.success('保存成功');
		dialogVisible.value = false;
		emit('success', formData);
	} finally {
		submitting.value = false;
	}
};
</script>

<style lang="scss" scoped>
.address-form {
	.section-title {
		font-size: 15px;
		font-weight: 500;
		position: relative;
		padding-left: 12px;

		&::before {
			content: '';
			position: absolute;
			left: 0;
			top: 50%;
			transform: translateY(-50%);
			width: 4px;
			height: 16px;
			background-color: var(--el-color-primary);
			border-radius: 0 2px 2px 0;
		}
	}

	.address-content {
		display: flex;
		gap: 20px;

		.sender-info,
		.receiver-info {
			flex: 1;
			border: 1px solid var(--el-border-color-lighter);
			border-radius: 4px;
			transition: all 0.3s;

			&.active {
				border-color: var(--el-color-primary);
				box-shadow: 0 0 0 1px var(--el-color-primary);
			}

			.section-header {
				padding: 12px;
				background-color: var(--el-fill-color-light);
				border-bottom: 1px solid var(--el-border-color-lighter);
				cursor: pointer;

				.title {
					font-size: 16px;
					font-weight: 500;
				}
			}

			.section-content {
				padding: 20px;
			}
		}

		.sender-info {
			.section-header {
				background-color: var(--el-color-warning-light-9);
				color: var(--el-color-warning-dark-2);
			}
		}

		.receiver-info {
			.section-header {
				background-color: var(--el-color-success-light-9);
				color: var(--el-color-success-dark-2);
			}
		}
	}
}

:deep(.el-form) {
	.el-form-item {
		margin-bottom: 18px;

		.el-form-item__label {
			padding-bottom: 4px;
			line-height: 20px;
			font-size: 14px;
			color: var(--el-text-color-regular);
		}

		.el-form-item__content {
			line-height: 32px;

			.el-input__wrapper {
				box-shadow: 0 0 0 1px #dcdfe6 inset;

				&:hover {
					box-shadow: 0 0 0 1px var(--el-border-color-hover) inset;
				}

				&.is-focus {
					box-shadow: 0 0 0 1px var(--el-color-primary) inset;
				}
			}
		}
	}
}
</style>
